/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.mq.service.schedulerservice.business.syncbusiness;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.NotificationMessageKey;
import com.ndp.fb.enums.account.AccountOperateType;
import com.ndp.fb.enums.connectionobject.EntrustConnectionObjectOperateType;
import com.ndp.fb.enums.page.PageOperateType;
import com.ndp.fb.exception.ResourceManager;
import com.ndp.fb.exception.ResourceMsgManager;
import com.ndp.fb.fbagent.service.OauthFbService;
import com.ndp.fb.fbagent.service.PageFBService;
import com.ndp.fb.model.fbagent.result.businesses.*;
import com.ndp.fb.model.fbagent.result.businesses.User;
import com.ndp.fb.model.fbagent.result.connectionobjects.FBConnectionObjects;
import com.ndp.fb.model.fbagent.result.connectionobjects.ObjectStoreUrls;
import com.ndp.fb.model.fbagent.result.entrustaccount.EntrustAccounts;
import com.ndp.fb.mq.api.producer.AssetsAlertProducerService;
import com.ndp.fb.mq.api.producer.EventNotificationMessageProducerService;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.mq.api.service.schedulerservice.FBUserSchedulerService;
import com.ndp.fb.mq.api.service.schedulerservice.business.syncbusiness.SyncAccountInfoService;
import com.ndp.fb.mq.api.service.schedulerservice.business.syncbusiness.SyncAccountResourceService;
import com.ndp.fb.mq.service.schedulerservice.business.FetchCustomaudiencesService;
import com.ndp.fb.rdb.api.*;
import com.ndp.fb.rdb.model.*;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceItem;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceTemplateAndConnectionObject;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.util.ThreadPool;
import com.restfb.json.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author giser.yang
 * @Title: SyncAccountInfoServiceImpl.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 下午2:30:54
 */
@Service
public class SyncAccountInfoServiceImpl implements SyncAccountInfoService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Reference
    SyncAccountResourceService syncAccountResourceService;
    @Reference
    EntrustAccountRdbService entrustAccountRdbService;
    @Reference
    ProductConfigurationRdbService poductConfigurationRdbServices;
    @Autowired
    AdAccountsSchedulerService adaccountsSchedulerService;
    @Reference
    PagePermissionRdbService pagePermissionRdbService;
    @Reference
    PageRdbService pageRdbService;
    @Autowired
    FBUserSchedulerService fbUserSchedulerService;
    @Reference
    PageFBService pageFBService;
    @Reference
    FbUserRdbService fbUserRdbService;
    @Reference
    BusinessManagerRdbService businessManagerRdbService;
    @Reference
    FbUserBusinessRdbService fbUserBusinessRdbService;
    @Autowired
    EventNotificationMessageProducerService eventNotificationMessageProducerService;
    @Reference
    FbUserPermissionRdbService fbUserPermissionRdbService;
    @Reference
    private OauthFbService oauthFbService;
    @Reference
    private ConnectionObjectRdbService connectionObjectRdbService;
    @Reference
    private EntrustAccountConnectionObjectsRdbService entrustAccountConnectionObjectsRdbService;
    @Reference
    private CustomAudienceTemplateRdbService customAudienceTemplateRdbService;
    @Autowired
    private FetchCustomaudiencesService fetchCustomaudiencesService;
    @Reference
    private CustomAudienceRdbService customAudienceRdbService;
    @Autowired
    private AssetsAlertProducerService assetsAlertProducerService;


    /**
     * @param
     * @discription
     * @author giser.yang 创建时间 2015年6月9日 下午2:31:06
     */

    @Override
    public void syncAccountInfo() {
        ThreadPool.execute(() -> {
            try {

                List<Long> entrustAccountIds = new ArrayList<>();
                List<EntrustAccount> entrustAccounts = entrustAccountRdbService.findAdAccountListByRoles("ADMIN", "GENERAL_USER", "REPORTS_ONLY");
                if (CollectionUtils.isEmpty(entrustAccounts)) {
                    logger.warn("系统没有广告账号!");
                    return;
                }
                for (EntrustAccount entrustAccount : entrustAccounts) {
                    Long fbAccountId = entrustAccount.getFbAccountId();
                    if (entrustAccountIds.contains(fbAccountId)) {
                        logger.info("账号" + fbAccountId + "账号已经被同步!");
                        continue;
                    }
                    String token = adaccountsSchedulerService.getAdaccountsToken(fbAccountId);
                    if (StringUtils.isEmpty(token)) {
                        logger.info("账号" + fbAccountId + "账号没有可用的token!");
                        continue;
                    }
                    entrustAccountIds.add(fbAccountId);
                    try {
                        //通过facebook接口获取该账号下的应用列表
                        List<FBConnectionObjects> getFacebookConnectionObjects = getConnectionObjectByAccessToken(entrustAccount, token);
                        //同步该账号下的应用列表到数据库，并返回该用户新增应用列表及删除应用列表
                        syncConnectionObjectInfoNew(entrustAccount, getFacebookConnectionObjects);
                    } catch (Exception e) {
                        logger.error("fbConnectionObjectsList sync error:entrustAccount:"
                                + entrustAccount.getFbAccountId());
                        logger.error(e.getMessage(), e);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        });

    }

    //giser 2015-12-16 修改
    private void syncConnectionObjectInfoNew(EntrustAccount entrustAccount, List<FBConnectionObjects> fbConnectionObjectsList) {
        if (CollectionUtils.isEmpty(fbConnectionObjectsList)) {
            return;
        }
        //将facebook应用对象转换为本地对象
        List<ConnectionObject> fbConnectionObjects = this.fbConnectionObject2ConnectionObject(fbConnectionObjectsList);

        //构造之后进行交叉判断的MAP
        Map<Long, ConnectionObject> fbConnectionObjectMap = new HashMap<Long, ConnectionObject>();
        if (CollectionUtils.isNotEmpty(fbConnectionObjects)) {
            //账号下有授权的应用
            for (ConnectionObject connectionObject : fbConnectionObjects) {
                fbConnectionObjectMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);
            }
        }

        //返回该账号下的数据库应用列表
        List<ConnectionObject> dbConnectionObjectList = connectionObjectRdbService.findByFbAccountId(entrustAccount.getFbAccountId());

        //数据库己存储的应用map
        Map<Long, ConnectionObject> dbConnectionObjectMap = new HashMap<Long, ConnectionObject>();
        if (CollectionUtils.isNotEmpty(dbConnectionObjectList)) {
            //账号下有授权的应用
            for (ConnectionObject connectionObject : dbConnectionObjectList) {
                dbConnectionObjectMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);
            }
        }

        //找出facebook有我们没有的应用,新增到数据库中
        if (CollectionUtils.isNotEmpty(fbConnectionObjects)) {
            //facebook应用对象列表
            for (ConnectionObject connectionObject : fbConnectionObjects) {
                if (!dbConnectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId())) {
                    logger.info("同步应用,账号{}下新增应用{}", entrustAccount.getFbAccountId(), connectionObject.getFbConnectionObjectId());
                    this.saveOrUpdateConnectionObject(entrustAccount, connectionObject);

                    //查询该应用是否对应的有自定义受众模板,如果有且该账号未与该自定受众模板没有对应关系则需要同步该应用对应的自定义受众
                    List<CustomAudienceTemplateAndConnectionObject> customAudienceTemplateList = customAudienceTemplateRdbService.getConnectionObjectByConnectionId(connectionObject.getFbConnectionObjectId());
                    if (ListUtil.isNotEmpty(customAudienceTemplateList)) {
                        for (CustomAudienceTemplateAndConnectionObject item : customAudienceTemplateList) {
                            Long customAudienceTemplateId = item.getCustomAudienceTemplateId();
                            List<CustomAudienceItem> customAudienceItems = customAudienceRdbService.findByTemplateIdAndAccountId(customAudienceTemplateId, entrustAccount.getFbAccountId());
                            if (customAudienceItems == null || customAudienceItems.size() == 0) {
                                fetchCustomaudiencesService.addCustomaudiences(entrustAccount.getFbAccountId(), customAudienceTemplateId);
                            }
                        }
                    }

                }
            }
        } else {
            //facebook的应用为空，纪录日志回头报警
            logger.warn("notice:同步应用,账号{}下应用列表为空", entrustAccount.getFbAccountId());
        }

        //找出我们有，facebook没有的应用从我们的数据库中删除
        if (CollectionUtils.isNotEmpty(dbConnectionObjectList)) {
            List<EntrustAccountConnectionObjects> delete = new ArrayList<>();
            List<Long> deleteConnObjectIds = new ArrayList<>();
            for (ConnectionObject connectionObject : dbConnectionObjectList) {
                if (!fbConnectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId())) {
                    logger.info("同步应用,账号{}下删除应用{}", entrustAccount.getFbAccountId(), connectionObject.getFbConnectionObjectId());

                    //数据库有，facebook中没有
                    EntrustAccountConnectionObjects e = new EntrustAccountConnectionObjects();
                    e.setFbAccountId(entrustAccount.getFbAccountId());
                    e.setFbConnectionObjectId(connectionObject.getFbConnectionObjectId());
                    delete.add(e);
                    deleteConnObjectIds.add(connectionObject.getFbConnectionObjectId());
                }
            }
            if (CollectionUtils.isNotEmpty(delete)) {
                entrustAccountConnectionObjectsRdbService.batchDeleteEntrustAccountConnectionObjects(delete);
            }

            //查询该应用对应的自定义受众账号项,将其删除
            if (CollectionUtils.isNotEmpty(deleteConnObjectIds)) {
                logger.info("开始删除被删除的应用ids");
                customAudienceRdbService.deleteByFbConnObjIds(deleteConnObjectIds, ResourceMsgManager.getResource("zh_CN", "CUSTOM_AUDIENCE_DEL_REASON_BY_CONN_OBJECT"));
                customAudienceTemplateRdbService.batchDelCustomAudienceTemplFbConnObjByConnId(deleteConnObjectIds);
            }
        }

        //找出变更的应用
        getNeedUpdateConnectionObjectToDb(fbConnectionObjectMap, dbConnectionObjectList);
        syncObjectStoreUrls(fbConnectionObjectsList);

    }

    private void getNeedUpdateConnectionObjectToDb(Map<Long, ConnectionObject> fbConnectionObjectMap, List<ConnectionObject> dbConnectionObjectList) {
        if (CollectionUtils.isNotEmpty(dbConnectionObjectList)) {

            logger.info("========找出变更的应用========" + dbConnectionObjectList.size() + "个");
            List<ConnectionObject> connectionObjectList = new ArrayList<>();
            for (ConnectionObject connectionObject : dbConnectionObjectList) {
                if (fbConnectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId())) {

                    ConnectionObject fbConnectionObject = (ConnectionObject) fbConnectionObjectMap.get(connectionObject.getFbConnectionObjectId());
                    if ((fbConnectionObject.getIconUrl() != null && !fbConnectionObject.getIconUrl().equals(connectionObject.getIconUrl()))
                            || (fbConnectionObject.getIconUrl() == null && connectionObject.getIconUrl() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getFbConnectionObjectId() != null && !fbConnectionObject.getFbConnectionObjectId().equals(connectionObject.getFbConnectionObjectId()))
                            || (fbConnectionObject.getFbConnectionObjectId() == null && connectionObject.getFbConnectionObjectId() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getLogoUrl() != null && !fbConnectionObject.getLogoUrl().equals(connectionObject.getLogoUrl()))
                            || (fbConnectionObject.getLogoUrl() == null && connectionObject.getLogoUrl() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if (fbConnectionObject.getName() != null && !fbConnectionObject.getName().equals(connectionObject.getName())
                            || (fbConnectionObject.getName() == null && connectionObject.getName() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getNativeAppStoreIds() != null && !fbConnectionObject.getNativeAppStoreIds().equals(connectionObject.getNativeAppStoreIds()))
                            || (fbConnectionObject.getNativeAppStoreIds() == null && connectionObject.getNativeAppStoreIds() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getObjectStoreUrls() != null && !fbConnectionObject.getObjectStoreUrls().equals(connectionObject.getObjectStoreUrls()))
                            || (fbConnectionObject.getObjectStoreUrls() == null && connectionObject.getObjectStoreUrls() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getNativeAppTargetingIds() != null && !fbConnectionObject.getNativeAppTargetingIds().equals(connectionObject.getNativeAppTargetingIds()))
                            || (fbConnectionObject.getNativeAppTargetingIds() == null && connectionObject.getNativeAppTargetingIds() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getPicture() != null && !fbConnectionObject.getPicture().equals(connectionObject.getPicture()))
                            || (fbConnectionObject.getPicture() == null && connectionObject.getPicture() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getProductType() != null && !fbConnectionObject.getProductType().equals(connectionObject.getProductType()))
                            || (fbConnectionObject.getProductType() == null && connectionObject.getProductType() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getSupportedPlatforms() != null && !fbConnectionObject.getSupportedPlatforms().equals(connectionObject.getSupportedPlatforms()))
                            || (fbConnectionObject.getSupportedPlatforms() == null && connectionObject.getSupportedPlatforms() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getType() != null && !fbConnectionObject.getType().equals(connectionObject.getType()))
                            || (fbConnectionObject.getType() == null && connectionObject.getType() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }
                    if ((fbConnectionObject.getUrl() != null && !fbConnectionObject.getUrl().equals(connectionObject.getUrl()))
                            || (fbConnectionObject.getUrl() == null && connectionObject.getUrl() != null)) {
                        connectionObjectList.add(fbConnectionObject);
                        continue;
                    }

                }
            }

            for (ConnectionObject connectionObject : connectionObjectList) {
                logger.info("找出变更的应用名称:" + connectionObject.getName() + ",facebook应用id:" + connectionObject.getFbConnectionObjectId());
                connectionObjectRdbService.saveorupdateConnectionObject(connectionObject);
            }
        }
    }

    private void syncConnectionObjectInfo(Map<String, List<ConnectionObject>> newAddConnectionObjectsMap, Map<String, List<ConnectionObject>> newAddPagesMap, Map<String, List<ConnectionObject>> deleteConnectionObjectsMap, EntrustAccount entrustAccount, List<FBConnectionObjects> fbConnectionObjectsList) {

        Map<Long, ConnectionObject> connectionObjectMap = new HashMap<>();
        Map<Long, ConnectionObject> pageMap = new HashMap<>();
        List<ConnectionObject> newAddConnectionObjects = new ArrayList<ConnectionObject>();
        List<ConnectionObject> newAddPages = new ArrayList<ConnectionObject>();
        List<ConnectionObject> deleteConnectionObjects = new ArrayList<ConnectionObject>();

        List<ConnectionObject> connectionObjects = this.fbConnectionObject2ConnectionObject(fbConnectionObjectsList);

        //增加新的应用到数据库
        if (CollectionUtils.isNotEmpty(connectionObjects)) {
            for (ConnectionObject connectionObject : connectionObjects) {
                EntrustAccountConnectionObjects entrustAccountConnectionObjects = entrustAccountConnectionObjectsRdbService.findEntrustAccountConnectionObjectByFbAccountIdAndFbConnectionObjectId(entrustAccount.getFbAccountId(), connectionObject.getFbConnectionObjectId());
                //如果数据库不存在就新增应用并增加账号与应用对应关系
                if (entrustAccountConnectionObjects == null) {
                    if (!connectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId()) && connectionObject.getType().intValue() == 2) {
                        newAddConnectionObjects.add(connectionObject);
                    }
                    if (!pageMap.containsKey(connectionObject.getFbConnectionObjectId()) && connectionObject.getType().intValue() == 1) {
                        newAddPages.add(connectionObject);
                    }

                }
                if (connectionObject.getType().intValue() == 2) {
                    connectionObjectMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);

                }
                if (connectionObject.getType().intValue() == 1) {
                    pageMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);
                }
            }
        }

        //删除不存在的应用从数据库
        List<ConnectionObject> dbConnectionObjectList = connectionObjectRdbService.findByFbAccountId(entrustAccount.getFbAccountId());
        Map<Long, ConnectionObject> deleteConnectionObjectMap = new HashMap<Long, ConnectionObject>();
        if (CollectionUtils.isNotEmpty(dbConnectionObjectList)) {
            for (ConnectionObject connectionObject : dbConnectionObjectList) {
                if (!connectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId())) {
                    if (!deleteConnectionObjectMap.containsKey(connectionObject.getFbConnectionObjectId())) {
                        deleteConnectionObjects.add(connectionObject);
                    }
                    deleteConnectionObjectMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);
                }
            }
        }

        //按用户加入各自新增或删除的应用集合
        List<AdaccountPermissionExt> adaccountPermissionExts = fbUserPermissionRdbService.getUserpermissionExts(entrustAccount.getFbAccountId());
        for (AdaccountPermissionExt adaccountPermissionExt : adaccountPermissionExts) {
            String userId = adaccountPermissionExt.getUserId();
            newAddConnectionObjectsMap.put(userId, newAddConnectionObjects);
            deleteConnectionObjectsMap.put(userId, deleteConnectionObjects);
            newAddPagesMap.put(userId, newAddPages);
        }

        syncObjectStoreUrls(fbConnectionObjectsList);
    }

    /**
     * 保存更新应用对象
     *
     * @param entrustAccount
     * @param connectionObject
     */
    private void saveOrUpdateConnectionObject(EntrustAccount entrustAccount, ConnectionObject connectionObject) {
        connectionObjectRdbService.saveorupdateConnectionObject(connectionObject);
        EntrustAccountConnectionObjects entrustAccountConnectionObjects = new EntrustAccountConnectionObjects();
        entrustAccountConnectionObjects.setFbAccountId(entrustAccount.getFbAccountId());
        entrustAccountConnectionObjects.setFbConnectionObjectId(connectionObject.getFbConnectionObjectId());
        entrustAccountConnectionObjectsRdbService.saveEntrustAccountConnectionObject(entrustAccountConnectionObjects);
        //通知应用新增到消息中心
        assetsAlertProducerService.notificationAppAlert(null, entrustAccount.getFbAccountId(), null, connectionObject.getFbConnectionObjectId(), EntrustConnectionObjectOperateType.ADD);
    }


    /**
     * 将FB广告帐号转为系统使用的广告帐号
     *
     * @param entrustAccounts
     * @return
     */
    private List<EntrustAccountExt> FBEntrustAccount2EntrustAccount(List<EntrustAccounts> entrustAccounts) {
        List<EntrustAccountExt> entrustAccountList = new ArrayList<>();
        for (EntrustAccounts fbEntrustAccount : entrustAccounts) {
            EntrustAccountExt entrustAccount = new EntrustAccountExt();
            entrustAccount.setFbAccountId(Long.parseLong(fbEntrustAccount.getAccountId()));
            entrustAccount.setTimezone(fbEntrustAccount.getTimezoneName());
            if (StringUtil.isNotEmpty(fbEntrustAccount.getTosAccepted())) {
                JsonObject jsonObject = new JsonObject(fbEntrustAccount.getTosAccepted());
                if (jsonObject.has("custom_audience_tos"))
                    entrustAccount.setCustomAudienceTos(jsonObject.getInt("custom_audience_tos"));
            }
            entrustAccount.setAccountStatus(fbEntrustAccount.getAccountStatus());
            entrustAccount.setName(fbEntrustAccount.getName());
            entrustAccount.setBalance(fbEntrustAccount.getBalance());
            entrustAccount.setCreateTime(new Date());
            entrustAccount.setUpdateTime(new Date());
            entrustAccountList.add(entrustAccount);
        }
        return entrustAccountList;
    }

    public boolean saveOrUpdate(List<EntrustAccount> entrustAccounts,
                                String userId) {
        // 数据同步 需要保存list和更新list
        List<EntrustAccount> dbEntrustAccounts = entrustAccountRdbService.findAllWithOutAccount();

        List<EntrustAccount> needUpdateEntrustAccounts = new ArrayList<>();
        List<EntrustAccount> needSaveEntrustAccounts = new ArrayList<>();

        if (!CollectionUtils.isEmpty(dbEntrustAccounts)) {
            int dbEntrustAccountsSize = dbEntrustAccounts.size();
            // 过滤出需要更新的数据
            for (int i = 0; i < dbEntrustAccountsSize; i++) {
                EntrustAccount dbEntrustAccount = dbEntrustAccounts.get(i);
                dbEntrustAccount.setIsDelete(1);

                for (int j = 0; j < entrustAccounts.size(); j++) {
                    // 类型需要转换,类型错误
                    EntrustAccount fbEntrustAccount = entrustAccounts.get(j);
                    if (fbEntrustAccount.getFbAccountId().compareTo(dbEntrustAccount.getFbAccountId()) == 0) {
                        needUpdateEntrustAccounts.add(fbEntrustAccount);// 将需要更新的保存起来,方便后面做保存过滤使用
                        dbEntrustAccount.setIsDelete(0);// 更新为可用
                        dbEntrustAccount.setEmail(fbEntrustAccount.getEmail());
                        dbEntrustAccount.setBalance(fbEntrustAccount.getBalance());
                        dbEntrustAccount.setCreateTime(fbEntrustAccount.getCreateTime());
                        dbEntrustAccount.setName(fbEntrustAccount.getName());
                        dbEntrustAccount.setTimezone(fbEntrustAccount.getTimezone());
                        break;
                    }
                }
                dbEntrustAccounts.set(i, dbEntrustAccount);// 将需要更新过的数据保存
            }

            // 过滤掉 fbEntrustAccounts 中, 已经存在数据库中的数据,剩下的就是需要新增的
            for (int i = 0; i < entrustAccounts.size(); i++) {
                EntrustAccount entrustAccount = entrustAccounts.get(i);
                boolean isExists = false;// 判断
                for (int j = 0; j < needUpdateEntrustAccounts.size(); j++) {
                    EntrustAccount needUpdateEntrustAccount = needUpdateEntrustAccounts.get(j);
                    if (entrustAccount.getFbAccountId().compareTo(needUpdateEntrustAccount.getFbAccountId()) == 0) {
                        isExists = true;
                        break;
                    }
                }
                if (!isExists) {
                    needSaveEntrustAccounts.add(entrustAccount);
                }
            }

            entrustAccountRdbService.batchUpdateAdAccount(dbEntrustAccounts);
            entrustAccountRdbService.batchDeleteAccounts(needSaveEntrustAccounts);
            entrustAccountRdbService.batchSaveAccounts(needSaveEntrustAccounts);
            return true;

        } else {
            return false;
        }

    }

    private List<FBConnectionObjects> getConnectionObjectByAccessToken(EntrustAccount entrustAccount, String accessToken) {
        // 调用 apiagent,返回 ConnectObject 列表
        return oauthFbService.getFBConnectionObjects(entrustAccount.getFbAccountId(), accessToken);
    }


    /**
     * 同步 product_configuration
     * 根据其object_store_urls字段，解析成product_configuration入库
     * <p>
     * 对于type为2的，根据其object_store_urls字段，解析成product_configuration入库。
     * connection_object和product_configuration是1：M的关系。 如： "object_store_urls": {
     * "google_play":
     * "http://play.google.com/store/apps/details?id=com.cleanmaster.mguard"，
     * "fb_canvas": "http://localhost:8080/fblogin/loginsucess.html" }
     * 可以解析成两条product_configuration记录， platform_version object_store_url
     * google_play
     * http://play.google.com/store/apps/details?id=com.cleanmaster.mguard
     * fb_canvas http://localhost:8080/fblogin/loginsucess.html
     *
     * @return
     */
    private List<ProductConfiguration> syncObjectStoreUrls(List<FBConnectionObjects> fbConnectionObjectsList) {

        if (fbConnectionObjectsList == null
                || fbConnectionObjectsList.size() == 0) {
            return null;
        }
        for (FBConnectionObjects fbConnectionObjects : fbConnectionObjectsList) {
            List<ProductConfiguration> productConfigurationList = new ArrayList();
            ObjectStoreUrls objectStoreUrls = fbConnectionObjects.getObjectStoreUrls();

            String fbCanvas = objectStoreUrls == null ? "" : objectStoreUrls.getFbCanvas();
            String googlePlay = objectStoreUrls == null ? "" : objectStoreUrls.getGooglePlay();
            String itunes = objectStoreUrls == null ? "" : objectStoreUrls.getItunes();
            String itunesIpad = objectStoreUrls == null ? "" : objectStoreUrls.getItunesIpad();
            String windowsStore = objectStoreUrls == null ? "" : objectStoreUrls.getWindowsStore();

            if (StringUtil.isNotEmpty(fbCanvas)) {
                ProductConfiguration productConfiguration = new ProductConfiguration();
                productConfiguration.setFbConnectionObjectId(Long.parseLong(fbConnectionObjects.getId()));
                productConfiguration.setObjectStoreUrl(fbCanvas);
                productConfiguration.setPlatform("fb_canvas");
                productConfigurationList.add(productConfiguration);
            }

            if (StringUtil.isNotEmpty(googlePlay)) {
                ProductConfiguration productConfiguration = new ProductConfiguration();
                productConfiguration.setFbConnectionObjectId(Long.parseLong(fbConnectionObjects.getId()));
                productConfiguration.setObjectStoreUrl(googlePlay);
                productConfiguration.setPlatform("google_play");
                productConfigurationList.add(productConfiguration);
            }

            if (StringUtil.isNotEmpty(itunes)) {
                ProductConfiguration productConfiguration = new ProductConfiguration();
                productConfiguration.setFbConnectionObjectId(Long.parseLong(fbConnectionObjects.getId()));
                itunes = processUrl(itunes);
                productConfiguration.setObjectStoreUrl(itunes);
                productConfiguration.setPlatform("itunes");
                productConfigurationList.add(productConfiguration);
            }

            if (StringUtil.isNotEmpty(itunesIpad)) {
                ProductConfiguration productConfiguration = new ProductConfiguration();
                productConfiguration.setFbConnectionObjectId(Long.parseLong(fbConnectionObjects.getId()));
                itunesIpad = processUrl(itunesIpad);
                productConfiguration.setObjectStoreUrl(itunesIpad);
                productConfiguration.setPlatform("itunes_ipad");
                productConfigurationList.add(productConfiguration);
            }
            if (StringUtil.isNotEmpty(windowsStore)) {
                ProductConfiguration productConfiguration = new ProductConfiguration();
                productConfiguration.setFbConnectionObjectId(Long.parseLong(fbConnectionObjects.getId()));
                productConfiguration.setObjectStoreUrl(windowsStore);
                productConfiguration.setPlatform("windows_store");
                productConfigurationList.add(productConfiguration);
            }
            if (CollectionUtils.isNotEmpty(productConfigurationList)) {
                // 数据同步
                this.saveOrUpdate(productConfigurationList, Long.valueOf(fbConnectionObjects.getId()));
            }

        }
        return null;

    }

    private String processUrl(String url) {
        String[] appIdUrl = url.split("app/id");
        if (appIdUrl.length == 2) {
            url = "https://itunes.apple.com/app/id" + url.split("app/id")[1];
        }
        return url;
    }

    /**
     * 将FB的ConnectionObject装成系统ConnectionObject
     *
     * @param fbConnectionObjectsList
     * @return
     */
    private List<ConnectionObject> fbConnectionObject2ConnectionObject(
            List<FBConnectionObjects> fbConnectionObjectsList) {
        List<ConnectionObject> connectionObjectList = new ArrayList<>();

        if (fbConnectionObjectsList == null
                || fbConnectionObjectsList.size() == 0) {
            return connectionObjectList;
        }
        for (FBConnectionObjects fbConnectionObjects : fbConnectionObjectsList) {
            ConnectionObject connectionObject = new ConnectionObject();
            connectionObject.setFbConnectionObjectId(Long
                    .parseLong(fbConnectionObjects.getId()));
            connectionObject.setName(fbConnectionObjects.getName());
            connectionObject.setUrl(fbConnectionObjects.getUrl());
            connectionObject.setType(fbConnectionObjects.getType());
            connectionObject.setSupportedPlatforms(fbConnectionObjects
                    .getSupportedPlatforms());
            connectionObject.setNativeAppStoreIds(fbConnectionObjects
                    .getNativeAppStoreIds());
            connectionObject.setNativeAppTargetingIds(fbConnectionObjects
                    .getNativeAppTargetingIds());
            connectionObject.setLogoUrl(fbConnectionObjects.getLogoUrl());
            connectionObject.setIconUrl(fbConnectionObjects.getIconUrl());
            connectionObject.setPicture(fbConnectionObjects.getPicture());
            connectionObjectList.add(connectionObject);
        }
        return connectionObjectList;
    }

    private boolean saveOrUpdate(
            List<ProductConfiguration> productConfigurations,
            Long fbConnectionObjectId) {
        ProductConfiguration dbProductConfiguration;
        for (ProductConfiguration productConfiguration : productConfigurations) {
            logger.info("保存或更新产品配置->fbConnectionObjectId:" + fbConnectionObjectId + "->Platform:" + productConfiguration.getPlatform());
            try {
                productConfiguration.setFbConnectionObjectId(fbConnectionObjectId);
                dbProductConfiguration = poductConfigurationRdbServices
                        .findByFbConnectionObjectIdAndPlatForm(fbConnectionObjectId, productConfiguration.getPlatform());
                if (null == dbProductConfiguration) {
                    //save
                    poductConfigurationRdbServices.saveProductConfiguration(productConfiguration);
                } else {
                    if ((dbProductConfiguration.getObjectStoreUrl() != null && !dbProductConfiguration.getObjectStoreUrl().equals(productConfiguration.getObjectStoreUrl()))
                            || (dbProductConfiguration.getObjectStoreUrl() == null && productConfiguration.getObjectStoreUrl() != null)) {
                        //update
                        poductConfigurationRdbServices.update(productConfiguration);
                    }
                }
            } catch (Exception e) {
                logger.info("保存或更新产品配置失败->fbConnectionObjectId:" + fbConnectionObjectId + "->Platform:" + productConfiguration.getPlatform());
                logger.error(e.getMessage(), e);
            }
        }

        return true;

    }

    public boolean saveOrUpdate(List<ConnectionObject> connectionObjects,
                                EntrustAccount entrustAccount) {
        Map<Long, ConnectionObject> connectionObjectMap = new HashMap<>();
        List<ConnectionObject> dbConnectionObjectList = connectionObjectRdbService
                .findByFbAccountId(entrustAccount.getFbAccountId());

        if (CollectionUtils.isNotEmpty(connectionObjects)) {
            for (ConnectionObject connectionObject : connectionObjects) {
                connectionObjectMap.put(connectionObject.getFbConnectionObjectId(), connectionObject);
                connectionObjectRdbService.saveorupdateConnectionObject(connectionObject);
                EntrustAccountConnectionObjects e = new EntrustAccountConnectionObjects();
                e.setFbAccountId(entrustAccount.getFbAccountId());
                e.setFbConnectionObjectId(connectionObject.getFbConnectionObjectId());
                entrustAccountConnectionObjectsRdbService.saveEntrustAccountConnectionObject(e);
                assetsAlertProducerService.notificationAppAlert(null, entrustAccount.getFbAccountId(), null, connectionObject.getFbConnectionObjectId(), EntrustConnectionObjectOperateType.ADD);
            }
        }

        List<EntrustAccountConnectionObjects> delete = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dbConnectionObjectList)) {
            for (ConnectionObject dbConnectionObject : dbConnectionObjectList) {
                if (!connectionObjectMap.containsKey(dbConnectionObject.getFbConnectionObjectId())) {
                    //数据库有fb没有
                    EntrustAccountConnectionObjects e = new EntrustAccountConnectionObjects();
                    e.setFbAccountId(entrustAccount.getFbAccountId());
                    e.setFbConnectionObjectId(dbConnectionObject.getFbConnectionObjectId());
                    delete.add(e);
                }
            }

            if (CollectionUtils.isNotEmpty(delete)) {
                List<AdaccountPermissionExt> adaccountPermissionExts = fbUserPermissionRdbService.getUserpermissionExts(entrustAccount.getFbAccountId());
                for (AdaccountPermissionExt adaccountPermissionExt : adaccountPermissionExts) {
                    entrustAccountConnectionObjectsRdbService.batchDeleteEntrustAccountConnectionObjects(delete);
                }
            }
        }
        return true;
    }

    /**
     * @param userId
     * @discription
     * @author giser.yang 创建时间 2015年6月15日 下午2:00:05
     * @see SyncAccountInfoService#syncAccountInfo(java.lang.String)
     */

//    @Override
//    public void syncAccountInfo(final String userId) {
//
//        ThreadPool.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    List<Long> entrustAccountIds = new ArrayList<>();
//                    List<EntrustAccountExt> entrustAccounts = entrustAccountRdbService.findAdAccountListByUserIdAll(userId);
//
//                    Map<String, List<ConnectionObject>> newAddConnectionObjectsMap = new HashMap<String, List<ConnectionObject>>();
//                    Map<String, List<ConnectionObject>> deleteAddConnectionObjectsMap = new HashMap<String, List<ConnectionObject>>();
//                    Map<String, List<ConnectionObject>> newAddPagesMap = new HashMap<String, List<ConnectionObject>>();
//
//                    if (CollectionUtils.isEmpty(entrustAccounts)) {
//                        logger.warn("系统没有广告账号!");
//                        return;
//                    }
//                    for (EntrustAccount entrustAccount : entrustAccounts) {
//
//                        Long fbAccountId = entrustAccount.getFbAccountId();
//                        if (entrustAccountIds.contains(fbAccountId)) {
//                            logger.info("账号" + fbAccountId + "已经被同步!");
//
//                            continue;
//                        }
//                        String token = adaccountsSchedulerService.getAdaccountsToken(fbAccountId);
//                        if (StringUtils.isEmpty(token)) {
//                            logger.info("账号" + fbAccountId + "账号没有可用的token!");
//                            continue;
//                        }
//                        entrustAccountIds.add(fbAccountId);
//
//                        //获取该账号下的应用列表
//                        List<FBConnectionObjects> connectionObjects = getConnectionObjectByAccessToken(entrustAccount, token);
//
//                        //同步该账号下的应用列表到数据库，并返回该用户新增应用列表及删除应用列表
//                        syncConnectionObjectInfo(newAddConnectionObjectsMap, newAddPagesMap, deleteAddConnectionObjectsMap, entrustAccount, connectionObjects);
//
//                        //新增应用对象列表
//                        List<ConnectionObject> addConnectionObjects = newAddConnectionObjectsMap.get(userId);
//
//                        //发送新增应用消息
//                        addConnectionObjects.forEach(item->{
//                            assetsAlertProducerService.notificationAppAlert(userId,entrustAccount.getFbAccountId(),null,item.getFbConnectionObjectId(),EntrustConnectionObjectOperateType.ADD);
//
//                        });
//
//                        //删除应用对象列表
//                        List<ConnectionObject> deleteConnectionObjects = deleteAddConnectionObjectsMap.get(userId);
//
//                        //遍历加入所有应用ID
//                        List<Long> templateConnObjects = new ArrayList<Long>();
//                        for (ConnectionObject deleteConnObjectId : deleteConnectionObjects) {
//                            templateConnObjects.add(deleteConnObjectId.getId());
//                        }
//
//                        //查询该应用对应的自定义受众账号项,将其删除
//                        if (ListUtil.isNotEmpty(templateConnObjects)) {
//                            customAudienceRdbService.deleteByFbConnObjIds(templateConnObjects, ResourceMsgManager.getResource("zh_CN", "CUSTOM_AUDIENCE_DEL_REASON_BY_CONN_OBJECT"));
//                        }
//
//                        //删除应用通知
//                        deleteConnectionObjects.forEach(item->{
//                            assetsAlertProducerService.notificationAppAlert(userId,entrustAccount.getFbAccountId(),null,item.getFbConnectionObjectId(),EntrustConnectionObjectOperateType.DELETE);
//                        });
//
//                    }
//
//                } catch (Exception e) {
//                    logger.error(e.getMessage(), e);
//                }
//            }
//        });
//    }

    /**
     * @discription
     * @author giser.yang 创建时间 2015年6月19日 下午1:17:02
     * @see SyncAccountInfoService#
     */

    @Override
    public void syncPagesInfo() {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                Set<Long> ids = new HashSet<>();
                List<PagePermission> pagePermissions = pagePermissionRdbService
                        .getPagePermissionNotInPages();
                if (CollectionUtils.isEmpty(pagePermissions)) {
                    logger.info("没有需要同步的主页");
                }
                String token;
                for (PagePermission pagePermission : pagePermissions) {
                    if (!ids.contains(pagePermission.getPageId())) {
                        ids.add(pagePermission.getPageId());
                        token = fbUserRdbService.getTokenByFbUserId(pagePermission.getFbUserId());
                        syncPageInfo(pagePermission.getPageId(), token);
                    }
                }


            }
        });
    }

    /**
     * @param pageId
     * @discription
     * @author giser.yang 创建时间 2015年6月19日 下午1:18:11
     */

    @Override
    public void syncPageInfo(final Long pageId, final String token) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String pageIds = ConfigCentre.getString("page.ids", "");
                    if (pageIds.indexOf(pageId.toString()) > -1) {
                        logger.info("不去同步主页信息,主页ID:{}", pageId);
                        return;
                    }
                    FBPage fbPage = pageFBService
                            .getPageByPageId(pageId, token);
                    Page page = new Page();
                    page.setCanPost(fbPage.getCan_post());
                    page.setCategory(fbPage.getCategory());
                    page.setFbPageId(fbPage.getId());
                    page.setHasAndedApp(fbPage.getHas_added_app());
                    page.setIsCommunityPage(fbPage.getHas_added_app());
                    page.setIsPublished(fbPage.getIs_published());
                    page.setLikes(fbPage.getFan_count());
                    page.setLink(fbPage.getLink());
                    page.setName(fbPage.getName());
                    if (!StringUtils.isEmpty(fbPage.getPicture())) {
                        JSONObject data = JSONObject.parseObject(fbPage
                                .getPicture());
                        if (data != null && data.getJSONObject("data") != null) {
                            if (StringUtils.isNotEmpty(data.getJSONObject(
                                    "data").getString("url"))) {
                                page.setPictureUrl(data.getJSONObject("data")
                                        .getString("url"));
                            }
                        }
                    }
                    page.setTalkingAboutCount(fbPage.getTalking_about_count());
                    page.setWereHereCount(fbPage.getWere_here_count());
                    pageRdbService.saveorupdatePage(page);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

    }

    /**
     * @discription
     * @author giser.yang 创建时间 2015年6月22日 下午9:47:32
     */

    @Override
    public void syncPermission() {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<FbUser> fbUsers = fbUserRdbService.getAllFbUser();
                    String accessToken;
                    for (FbUser fbUser : fbUsers) {

                        logger.info("开始同步用户:" + fbUser.getUserId() + "权限信息!");

                        try {
                            accessToken = fbUser.getAccessToken();
                            List<FBBusinesses> fbBusinessesList = oauthFbService.getFbBusinessesList(fbUser.getAccessToken());
                            List<AdAccountPermission> adaccountPpermissionList;
                            List<AdAccountPermission> adaccountPpermissionList1;
                            List<PagePermission> pagePermissionList;
                            List<PagePermission> pagePermissionList1;
                            List<EntrustAccountExt> updateAccounts = new ArrayList<>();
                            List<EntrustAccountExt> recycleAccounts = new ArrayList<>();
                            List<EntrustAccountExt> updateAccounts1;
                            List<EntrustAccountExt> recycleAccounts1;
                            BusinessManager businessManager;
                            List<BusinessManager> businessManagers = new ArrayList<>();
                            List<EntrustAccounts> entrustAccountes = oauthFbService.getEntrustAccountsByFbUser(accessToken, 0, CommonConstants.NUM_INT_500, true);

                            if (CollectionUtils.isNotEmpty(fbBusinessesList)) {
                                //保存当前所有的账号信息
                                List<EntrustAccountExt> entrustAccountList2 = FBEntrustAccount2EntrustAccount(entrustAccountes);
                                for (EntrustAccount entrustAccount : entrustAccountList2) {
                                    if (entrustAccount.getAccountStatus() == 1) {
                                        entrustAccountRdbService.saveorupdateAdaccount(entrustAccount);
                                    }
                                }
                                for (FBBusinesses fbBusinesses : fbBusinessesList) {
                                    if (fbBusinesses != null && StringUtil.isNotEmpty(fbBusinesses.getId())) {
                                        businessManager = new BusinessManager(Long.parseLong(fbBusinesses.getId()), fbBusinesses.getName(), new Date());
                                        businessManagerRdbService.saveBusinessManager(businessManager);
                                        businessManagers.add(businessManager);
                                    }
                                }
                            }

                            Map<Long, BusinessManager> fbBmMap = new HashMap<>();
                            if (!CollectionUtils.isEmpty(businessManagers)) {
                                for (BusinessManager businessManager1 : businessManagers) {
                                    fbBmMap.put(businessManager1.getFbBusinessesId(), businessManager1);
                                }
                            }

                            //删除掉用户已经不在的企业,这个操作只有在用户点了同步并确定之后进行
                            List<FbUserBusinessManager> dbUserBusinessManagers = fbUserBusinessRdbService.getFbUserBusinessManagersByFbUserId(fbUser.getFbUserId());

                            Map<Long, FbUserBusinessManager> dbBmMap = new HashMap<>();
                            if (!CollectionUtils.isEmpty(dbUserBusinessManagers)) {
                                for (FbUserBusinessManager businessManager1 : dbUserBusinessManagers) {
                                    dbBmMap.put(businessManager1.getFbBusinessId(), businessManager1);
                                }
                            }

                            if (!CollectionUtils.isEmpty(dbUserBusinessManagers)) {
                                for (FbUserBusinessManager fbUserBusinessManager : dbUserBusinessManagers) {
                                    if (!fbBmMap.containsKey(fbUserBusinessManager.getFbBusinessId())) {
                                        //这里只删除企业,因为后面存在数据库和facebook都没有的企业
                                        fbUserBusinessRdbService.deleteFbUserBusinessManager(fbUser.getFbUserId(), fbUserBusinessManager.getFbBusinessId());
                                    }
                                }
                            }

                            //处理facebook没有的企业
                            List<EntrustAccountExt> entrustAccountExts = entrustAccountRdbService.findAdAccountListByFBUserIdAll(fbUser.getFbUserId());
                            if (CollectionUtils.isNotEmpty(entrustAccountExts)) {
                                for (EntrustAccountExt entrustAccount : entrustAccountExts) {
                                    if (!fbBmMap.containsKey(entrustAccount.getFbBusinessId())) {
                                        AdAccountPermission userPermission = fbUserPermissionRdbService.getUserpermission(entrustAccount.getFbAccountId(), fbUser.getFbUserId(), entrustAccount.getFbBusinessId());
                                        if (userPermission != null) {
                                            logger.info("回收facebook下的企业{}的账号{}", entrustAccount.getFbBusinessId(), entrustAccount.getFbAccountId());
                                            userPermission.setStatus("DISABLE");
                                            fbUserPermissionRdbService.saveorupdateUserPermission(userPermission);
                                            assetsAlertProducerService.notificationAccountAlert(fbUser.getUserId(), entrustAccount.getFbAccountId(), AccountOperateType.DELETE);
                                        }
                                    }
                                }
                            }

                            if (CollectionUtils.isNotEmpty(fbBusinessesList)) {
                                adaccountPpermissionList = new ArrayList<>();
                                pagePermissionList = new ArrayList<>();
                                // 同步BM信息以及BM下账号信息
                                for (BusinessManager businessManager1 : businessManagers) {
                                    List<UserpermissionsResult> userpermissionsResults = oauthFbService.getUserpermissionsResult(accessToken, businessManager1.getFbBusinessesId(), 0, CommonConstants.NUM_INT_500, true);
                                    adaccountPpermissionList1 = getAdaccountPpermissionList(accessToken, businessManager1, fbUser.getFbUserId(), userpermissionsResults);
                                    if (!CollectionUtils.isEmpty(adaccountPpermissionList1)) {
                                        adaccountPpermissionList.addAll(adaccountPpermissionList1);
                                    }
                                    pagePermissionList1 = getPagePermissionList(accessToken, businessManager1, fbUser.getFbUserId(), userpermissionsResults);
                                    if (!CollectionUtils.isEmpty(pagePermissionList1)) {
                                        pagePermissionList.addAll(pagePermissionList1);
                                    }
                                    List<EntrustAccountExt> entrustAccountList = entrustAccountRdbService.findAdAccountListByFBUserIdAndBusinessIdAll(fbUser.getFbUserId(), businessManager1.getFbBusinessesId());
                                    if (CollectionUtils.isEmpty(entrustAccountList)) {
                                        entrustAccountList = new ArrayList<>();
                                    }
                                    recycleAccounts1 = getRecycleEntrustAccount(adaccountPpermissionList1, entrustAccountes, entrustAccountList);
                                    updateAccounts1 = getUpdateEntrustAccount(adaccountPpermissionList1, entrustAccountes, entrustAccountList);
                                    if (!CollectionUtils.isEmpty(recycleAccounts1)) {
                                        recycleAccounts.addAll(recycleAccounts1);
                                        logger.info("系统有回收账号{},facebook返回权限结果{}", JSONObject.toJSONString(recycleAccounts1), JSONObject.toJSONString(userpermissionsResults));
                                        logger.info("facebook返回企业{}", JSONObject.toJSONString(fbBusinessesList));
                                    }
                                    if (!CollectionUtils.isEmpty(updateAccounts1)) {
                                        updateAccounts.addAll(updateAccounts1);
                                    }

                                    StringBuffer bodySb = new StringBuffer("系统己收回以下账号：");
                                    List<String> accountNames = new ArrayList<String>();
                                    for (EntrustAccount entrustAccount : recycleAccounts1) {
                                        AdAccountPermission userPermission = fbUserPermissionRdbService.getUserpermission(entrustAccount.getFbAccountId(), fbUser.getFbUserId(), businessManager1.getFbBusinessesId());
                                        if (userPermission != null) {
                                            userPermission.setStatus("DISABLE");
                                            fbUserPermissionRdbService.saveorupdateUserPermission(userPermission);
                                            assetsAlertProducerService.notificationAccountAlert(fbUser.getUserId(), entrustAccount.getFbAccountId(), AccountOperateType.DELETE);
                                            accountNames.add(userPermission.getFbAccountId().toString());
                                        }
                                    }

                                    if (accountNames.size() > 0) {
                                        List<String> objects = new ArrayList<>(1);
                                        objects.add(Joiner.on(",").join(accountNames));
                                        eventNotificationMessageProducerService.sendMessage(fbUser.getUserId(), NotificationMessageKey.N_010, objects, "#!account");
                                    }
                                }

                                List<Long> ids = new ArrayList<>();
                                //如果本次增加或者删除账号了，则重新同步账号和图片的关系
//                                if (!CollectionUtils.isEmpty(recycleAccounts)) {
//                                    //已经没有权限的账号权限已从数据库中删除了
//                                    try {
//                                        syncAccountInfo(fbUser.getUserId());
//                                    } catch (Exception e) {
//                                        logger.error(e.getMessage(), e);
//                                    }
//                                }
                                if (!CollectionUtils.isEmpty(updateAccounts)) {
                                    for (EntrustAccount entrustAccount : updateAccounts) {
                                        ids.add(entrustAccount.getFbAccountId());
                                    }
                                }
                                //更新账号用户BM关系
                                for (AdAccountPermission userPermission : adaccountPpermissionList) {
                                    if (ids.contains(userPermission.getFbAccountId())) {
                                        AdAccountPermission oldAdAccountPermission = fbUserPermissionRdbService.getUserpermissionAllStatus(userPermission.getFbAccountId(), userPermission.getFbUserId(), userPermission.getFbBusinessId());
                                        if (oldAdAccountPermission != null && !oldAdAccountPermission.getRole().equals(userPermission.getRole())) {
                                            //广告账号权限更新为
                                            List<String> values = new ArrayList<String>(2);
                                            values.add(userPermission.getFbAccountId() + "");
                                            values.add(userPermission.getRole());
                                            eventNotificationMessageProducerService.sendMessage(fbUser.getUserId(), NotificationMessageKey.N_004, values, "#!account");
                                        }
                                        fbUserPermissionRdbService.saveorupdateUserPermission(userPermission);
                                        assetsAlertProducerService.notificationAccountAlert(fbUser.getUserId(), userPermission.getFbAccountId(), AccountOperateType.UPDATE);
                                    }
                                }
                                saveorupdatedeletePagePermission(pagePermissionList, fbUser.getFbUserId(), accessToken);
                            }
                        } catch (Exception ex) {
                            logger.error(ex.getMessage(), ex);
                        }

                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });


    }

    private void saveorupdatedeletePagePermission(
            List<PagePermission> pagePermissionList, Long fbUserId, String token) {

        FbUser fbUser = fbUserRdbService.getFbUserByFbUserId(fbUserId);
        List<PagePermission> pagePermissionDBList = pagePermissionRdbService
                .getPagePermissionsByFbUserId(fbUserId);
        Map<String, PagePermission> pagePermissionMap = new HashMap<>();
        for (PagePermission pagePermission : pagePermissionList) {
            pagePermissionMap.put(
                    "" + pagePermission.getPageId()
                            + pagePermission.getFbBusinessId()
                            + pagePermission.getFbUserId(), pagePermission);
        }

        StringBuffer sb = new StringBuffer("系统己收回以下主页：");
        for (PagePermission pagePermissionDB : pagePermissionDBList) {
            if (!pagePermissionMap.containsKey("" + pagePermissionDB.getPageId() + pagePermissionDB.getFbBusinessId() + pagePermissionDB.getFbUserId())) {
                // 数据库里面存在,Fb不存在的
                pagePermissionRdbService.deletePagePermission(pagePermissionDB);
                assetsAlertProducerService.notificationPageAlert(fbUser.getUserId(), null, null, pagePermissionDB.getPageId(), PageOperateType.DELETE);
            }
        }

        sb.append("的权限");

        for (PagePermission pagePermission : pagePermissionList) {
            pagePermissionRdbService.saveorupdatePagePermission(pagePermission);
            if (pagePermissionRdbService.getPagePermission(pagePermission.getPageId(), pagePermission.getFbUserId(), pagePermission.getFbBusinessId()) != null) {
                //更新
                assetsAlertProducerService.notificationPageAlert(fbUser.getUserId(), null, null, pagePermission.getPageId(), PageOperateType.UPDATE);
            } else {
                //新增
                assetsAlertProducerService.notificationPageAlert(fbUser.getUserId(), null, null, pagePermission.getPageId(), PageOperateType.ADD);
            }
        }
    }

    private List<AdAccountPermission> getAdaccountPpermissionList(
            String accessToken, BusinessManager bm, Long fbUserId,
            List<UserpermissionsResult> userpermissionsResults) {
        List<AdAccountPermission> adaccountPpermissionList = new ArrayList<>();

        Map<String, AdAccountPermission> adaccountPpermissionMap = new HashMap<String, AdAccountPermission>();

        if (userpermissionsResults == null
                || userpermissionsResults.size() == 0) {
            return adaccountPpermissionList;
        }

        for (UserpermissionsResult userpermissionsResult : userpermissionsResults) {
            if (userpermissionsResult != null) {

                User user = userpermissionsResult.getUser();
                if (user == null || StringUtil.isEmpty(user.getId())) {
                    continue;
                }

                String strFbUserId = String.valueOf(fbUserId);

                if (!strFbUserId.equals(user.getId())) {
                    continue;
                }
                FbUserBusinessManager fbUserBusinessManager = new FbUserBusinessManager();
                fbUserBusinessManager.setFbUserId(fbUserId);
                fbUserBusinessManager.setFbBusinessId(bm.getFbBusinessesId());
                fbUserBusinessManager.setRole(userpermissionsResult.getRole());
                fbUserBusinessManager.setStatus(userpermissionsResult.getStatus());
                fbUserBusinessRdbService.saveFbUserBusinessManager(fbUserBusinessManager);
                AdAccountPermission userPermission;
                List<FBAdaccountPermission> adaccountPermissions = userpermissionsResult
                        .getAdaccountPermissions();
                if (adaccountPermissions != null
                        && adaccountPermissions.size() > 0) {
                    for (FBAdaccountPermission adaccountPermission : adaccountPermissions) {
                        if (adaccountPermission != null) {
                            // 只导入状态为ACTIVE的账号
                            String status = StringUtil.isEmpty(adaccountPermission.getStatus()) ? "" : adaccountPermission.getStatus();
                            if ("ACTIVE".equals(status)) { //
                                userPermission = new AdAccountPermission();
                                String role = StringUtil.isEmpty(adaccountPermission.getRole()) ? "" : adaccountPermission.getRole();
                                Long accountId = Long.valueOf(adaccountPermission.getId().replace("act_", ""));
                                userPermission.setFbAccountId(accountId);
                                userPermission.setFbBusinessId(bm.getFbBusinessesId());
                                userPermission.setFbUserId(fbUserId);
                                userPermission.setRole(role);
                                userPermission.setStatus(status);
                                adaccountPpermissionMap.put(adaccountPermission.getId(), userPermission);
                            }
                        }
                    }
                }
            }
        }

        Set set = adaccountPpermissionMap.entrySet();
        for (Iterator it = set.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            adaccountPpermissionList
                    .add((AdAccountPermission) entry.getValue());
        }

        return adaccountPpermissionList;

    }

    private List<PagePermission> getPagePermissionList(String accessToken,
                                                       BusinessManager bm, Long fbUserId,
                                                       List<UserpermissionsResult> userpermissionsResults) {
        List<PagePermission> pagePermissionList = new ArrayList<>();
        if (userpermissionsResults == null || userpermissionsResults.size() == 0) {
            return pagePermissionList;
        }

        for (UserpermissionsResult userpermissionsResult : userpermissionsResults) {
            if (userpermissionsResult != null) {

                User user = userpermissionsResult.getUser();
                if (user == null || StringUtil.isEmpty(user.getId())) {
                    continue;
                }

                String strFbUserId = String.valueOf(fbUserId);

                if (!strFbUserId.equals(user.getId())) {
                    continue;
                }
                PagePermission pagePermission;
                List<FBPagePermission> fbPagePermissions = userpermissionsResult.getPagePermissions();
                if (!CollectionUtils.isEmpty(fbPagePermissions)) {
                    for (FBPagePermission fbPagePermission : fbPagePermissions) {
                        if (fbPagePermission != null) {
                            // 只导入状态为ACTIVE的账号
                            String status = StringUtil.isEmpty(fbPagePermission.getStatus()) ? "" : fbPagePermission.getStatus();
                            if ("ACTIVE".equals(status)) {
                                pagePermission = new PagePermission();
                                String role = StringUtil.isEmpty(fbPagePermission.getRole()) ? "" : fbPagePermission.getRole();
                                pagePermission.setPageId(fbPagePermission.getId());
                                pagePermission.setFbBusinessId(bm.getFbBusinessesId());
                                pagePermission.setFbUserId(fbUserId);
                                pagePermission.setRole(role);
                                pagePermission.setStatus(status);
                                pagePermissionList.add(pagePermission);
                            }
                        }
                    }
                }
            }
        }
        return pagePermissionList;

    }

    /**
     * 比较广告权限帐号和 entrustAccount 广告帐号,如果 act_{id} 相等和 account_status=1, 则数据入库,否则舍弃
     *
     * @param fbEntrustAccountsList
     * @param adaccountPpermissionList
     * @return
     */
    private List<EntrustAccounts> compareEntrustAccountListAndAdaccountPpermissionList(List<EntrustAccounts> fbEntrustAccountsList, List<AdAccountPermission> adaccountPpermissionList, Integer accountStatus) {
        List<EntrustAccounts> resultList = new ArrayList<>();
        for (AdAccountPermission adaccountPpermission : adaccountPpermissionList) {
            for (EntrustAccounts fbEntrustAccounts : fbEntrustAccountsList) {
                if ((fbEntrustAccounts.getId()).equals("act_" + adaccountPpermission.getFbAccountId()) && fbEntrustAccounts.getAccountStatus().equals(accountStatus)) {
                    fbEntrustAccounts.setRole(adaccountPpermission.getRole());
                    resultList.add(fbEntrustAccounts);
                    break;
                }

            }
        }
        return resultList;
    }

    private List<EntrustAccountExt> getRecycleEntrustAccount(List<AdAccountPermission> userPermissions, List<EntrustAccounts> entrustAccounts, List<EntrustAccountExt> entrustAccountList) {
        List<EntrustAccounts> entrustAccountses = compareEntrustAccountListAndAdaccountPpermissionList(entrustAccounts, userPermissions, 1);
        return compareRecyleEntrustccount(entrustAccountList, entrustAccountses);
    }

    private List<EntrustAccountExt> getUpdateEntrustAccount(
            List<AdAccountPermission> userPermissions, List<EntrustAccounts> entrustAccounts, List<EntrustAccountExt> entrustAccountList) {
        List<EntrustAccounts> entrustAccountses = compareEntrustAccountListAndAdaccountPpermissionList(entrustAccounts, userPermissions, 1);
        return compareChangeEntrustAccount(entrustAccountList, entrustAccountses);
    }

    private List<EntrustAccountExt> compareRecyleEntrustccount(List<EntrustAccountExt> entrustAccountList, List<EntrustAccounts> entrustAccountses) {
        List<EntrustAccountExt> resultList = new ArrayList<>();
        for (EntrustAccountExt entrustAccount : entrustAccountList) {
            boolean isFounded = false;
            for (EntrustAccounts entrustAccounts : entrustAccountses) {
                if (entrustAccounts.getAccountId().equals(entrustAccount.getFbAccountId().toString())) {
                    isFounded = true;
                    break;
                }
            }
            if (!isFounded) {
                resultList.add(entrustAccount);
            }
        }
        return resultList;
    }

    /**
     * compareChangeEntrustAccount
     *
     * @param entrustAccountList
     * @param entrustAccountses
     * @return
     */
    private List<EntrustAccountExt> compareChangeEntrustAccount(List<EntrustAccountExt> entrustAccountList, List<EntrustAccounts> entrustAccountses) {
        List<EntrustAccounts> resultEntrustAccountsList = new ArrayList<>();
        for (EntrustAccounts entrustAccounts : entrustAccountses) {
            for (EntrustAccountExt entrustAccount : entrustAccountList) {
                if (entrustAccount.getFbAccountId().toString().equals(entrustAccounts.getAccountId())) {
                    if (isChangeEntrustAccountInfo(entrustAccount, entrustAccounts)) {
                        resultEntrustAccountsList.add(entrustAccounts);
                    }
                    break;
                }
            }

        }
        List<EntrustAccountExt> resultList = this.FBEntrustAccount2EntrustAccount(resultEntrustAccountsList);
        return resultList;
    }

    private boolean isChangeEntrustAccountInfo(EntrustAccountExt entrustAccount,
                                               EntrustAccounts entrustAccounts) {
        if (!entrustAccounts.getName().equals(entrustAccount.getName())
                || !entrustAccounts.getBalance().equals(
                entrustAccount.getBalance())
                ) {
            return true;
        }
        if (!entrustAccount.getAccountStatus().equals(entrustAccounts.getAccountStatus())) {
            return true;
        }
        if (!entrustAccount.getRole().equals(entrustAccounts.getRole())) {
            return true;
        }
        return false;
    }

}
